package base;

import java.io.File;
import java.util.*;
import com.swabunga.spell.engine.SpellDictionaryHashMap;
import com.swabunga.spell.event.SpellChecker;

public class Driver
{
	public static SpellChecker checker;
	public static boolean aStar=false;
	
	public static void main(String[] args)
	{
		//load up a new dictionary
		try
		{
			SpellDictionaryHashMap dictionary=new SpellDictionaryHashMap(new File("dict/english.0"));
			checker=new SpellChecker(dictionary);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return;
		}
		
		Scanner scan=new Scanner(System.in);
		
		//init a few things
		System.out.println("First word?");
		char[] start=scan.nextLine().toCharArray();
		System.out.println("Second word?");
		char[] target=scan.nextLine().toCharArray();
		PriorityQueue<Word> list=new PriorityQueue<Word>(100,new WordHeuristic());
		list.add(new Word(start,target));
		HashMap<String,Word> map=new HashMap<String,Word>();
		Word found=null;
		
		int limit=0;
		
		boolean wasFound=false;
		
		System.out.println("\nSearching for the word...");
		while(!list.isEmpty() && limit<10000 && (!aStar || !wasFound))
		{
			Word head=list.poll();
			
			System.out.println(new String(head.getWord())+" "+head.getHeuristic());
			
			if(Arrays.equals(head.getWord(),target))
			{
				found=head;
				wasFound=true;
			}
			
			ArrayList<Word> newWords=head.mutate(checker);
			for(Word w:newWords)
			{
				if(!map.containsKey(new String(w.getWord())))
				{
				list.add(w);
				map.put(new String(w.getWord()),w);
				}
				else
				{
					Word w2=map.get(new String(w.getWord()));
					if(w2.getLevel()>w.getLevel())
					{
						list.remove(w2);
						list.add(w);
						map.put(new String(w.getWord()),w);
					}
				}
			}
			
			limit++;	
		}
		
		
		if(found!=null)
		{
			System.out.println("\nWord Found! Printing Path!\n");
			printPath(found);
		}
		else
		{
			System.out.println("Path not found!");
		}
		
		System.out.println("Iterations of program: "+limit);
		scan.close();
	}
	
	public static void printPath(Word word)
	{
		int score=0;
		score=printPath(word,score);
		System.out.println("\nScore: "+(score-2));
	}
	
	public static int printPath(Word word, int score)
	{
		score++;
		if(word.getParent()!=null)
			score=printPath(word.getParent(),score);
		System.out.println(word.getWord());
		
		return score;
	}
}
